const uuid = require('node-uuid');
/**
 * 发送成功消息
 * @param {*} wsConnect 
 * @param {*} msg 
 * @param {*} data 
 */
async function send_success(wsConnect,msg = '操作成功',data = {}){
    wsConnect.send(JSON.stringify({
        code: 200,
        msg: msg,
        data: data
    }));
}

/**
 * 发送失败消息
 * @param {*} wsConnect 
 * @param {*} msg 
 * @param {*} data 
 * @param {*} code 
 */
 async function send_error(wsConnect,msg = '操作异常',data = {},code = -200){
    wsConnect.send(JSON.stringify({
        code: code,
        msg: msg,
        data: data
    }));
}

var wsServerArr = {};

/**
 * 设置uuid
 * @param {*} wsConnect 
 * @param {*} n 对象最大长度
 * @param {*} del 超过最大长度是否删除（右进一左删一）
 */
async function set_uuid(wsConnect,n = 2000,del = true){
    let id = uuid.v4();
    let keys = Object.keys(wsServerArr)
    if(keys.length > n){
        if(del === true){
            let num = keys.length - n;
            for (let index = 0; index < num; index++) {
                delete wsServerArr[keys[index]];
            }
        }else{
            await send_error('连接池满了，请设置属性或者增大连接数量')
            throw new Error('连接池满了，请设置属性或者增大连接数量');
        }
    }
    //数据添加
    wsServerArr[id] = wsConnect;
    return id;
}

module.exports = {
    send_success:send_success,
    send_error:send_error,
    set_uuid:set_uuid
}